
import xmms_vis
import time
import sys

visualization = False
vis = 0

def init_visualization(xmms, dict):
    global visualization, vis
    print('querying for version')
    res = xmms.visualization_version()
    res.wait()
    if res.iserror():
        print("Visualization init failed")
        sys.exit(1)
        return
    else:
        version = res.value()
        if version < 1:
            print("Visualization too old.")
            sys.exit(1)
            return
    x = xmms
    print("vis_init")
    res = xmms.visualization_init()
    res.wait()
    if res.iserror():
        print("Visualization init failed")
        print(res.value())
        sys.exit(1)
        return

    print('res_handle')
    vis = x.visualization_init_handle(res)
    if vis <0:
        print("Something went wrong during initialization.")
        sys.exit(1)
        return

    print('prop_set')
    res = x.visualization_properties_set(vis, dict)
    res.wait()
    if(res.iserror()):
        print("Visualization init failed")
        print(res.value())
        sys.exit(1)
        return
    
    counter = 0
    while not x.visualization_started(vis) or counter == 3:
        res = x.visualization_start(vis)
        if x.visualization_errored(vis):
            print("Couldn't start visualization: %s" % x.get_last_error())
            sys.exit(1)
            return
        res.wait()
        x.visualization_start_handle(res)
        print(counter)
        counter += 1
    if counter == 3:
        visualization = False
        sys.exit(1)
        return

    vis = vis
    visualization = True
    print("visualization successful %i" % vis)


x = xmms_vis.XMMS('test')
x.connect()
init_visualization(x, {'type':'spectrum', 'stereo': '0'})
times = []
DATA_SIZE = 1024

try:
    while True:
        t = time.time()
        data = x.visualization_chunk_get(vis, 0, 0, DATA_SIZE)
        while len(data) == 0:
            data = x.visualization_chunk_get(vis, 0, 0, DATA_SIZE)
        times.append(time.time()-t)
except KeyboardInterrupt:
    pass
sum = reduce(lambda x,y: x+y, times, 0)
max = reduce(lambda x,y: x>y and x or y, times, 0)
min = reduce(lambda x,y: x<y and x or y, times, 1)
print("Average: ", sum*1.0/len(times))
print("Max: %s" % max)
print("Min: %s" % min)



